package com.shy.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shy.commonutils.result.R;
import com.shy.commonutils.util.MD5;
import com.shy.userservice.utils.CodeGenerator;
import com.shy.userservice.entity.User;
import com.shy.userservice.mapper.UserMapper;
import com.shy.userservice.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shy.userservice.utils.PasswordGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author RinMi
 * @since 2022-11-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private CodeGenerator codeGenerator;

    @Autowired
    private PasswordGenerator passwordGenerator;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送验证码
    @Override
    public boolean sendCode(String phone) {

        String code = codeGenerator.generate();
        if (StringUtils.isEmpty(code)) {
            return false;
        }

        redisTemplate.opsForValue().set(phone, code, 300, TimeUnit.SECONDS);


        System.out.println(redisTemplate.opsForValue().get(phone));

        //发送验证码
        //.....................//

        return true;

    }

    /*
     * 手机验证码登录：发送验证码、匹配登录信息（手机号、验证码）
     */
    @Override
    public R phoneLogin(String phone, String code) {

        String realCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(realCode)) {
            return R.error().message("验证码错误");
        }

        //检查数据库中是否存在该手机号
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);

        User user = baseMapper.selectOne(queryWrapper);

        //如果不存在该用户则系统自动注册
        if (user == null) {
            User insertUser = new User();
            insertUser.setPhone(phone);
            insertUser.setPassword(MD5.encrypt(passwordGenerator.generator()));
            insertUser.setNickname(phone);
            int insert = baseMapper.insert(insertUser);
            if (insert == 1) {
                return R.ok().message("注册成功");
            } else {
                return R.error().message("注册失败");
            }
        }

        return R.ok();
    }

    /*
     *  账号密码登录：匹配登录信息（账号、密码）
     */
    @Override
    public R login(String phone, String password) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.eq("password", MD5.encrypt(password));

        User user = baseMapper.selectOne(queryWrapper);
        if (user == null) {
            return R.error();
        }

        return R.ok();
    }

    /*
     *  手机号注册：手机号 + 验证码
     */
    @Override
    public boolean phoneRegister(String phone, String code) {

        String realCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(realCode)) {
            return false;
        }

        //判断该手机号是否已注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User user = baseMapper.selectOne(queryWrapper);

        if (user != null) {
            return false;
        }

        User insertUser = new User();
        insertUser.setPhone(phone);
        insertUser.setPassword(MD5.encrypt(passwordGenerator.generator()));
        insertUser.setNickname(phone);
        int insert = baseMapper.insert(insertUser);

        return insert == 1;
    }

    /*
     *  账号密码登录：手机号 + 密码
     */
    @Override
    public R register(String phone, String password) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.eq("password", MD5.encrypt(password));

        User user = baseMapper.selectOne(queryWrapper);
        if (user != null) {
            return R.error().message("该账号已注册");
        }
        User insertUser = new User();
        insertUser.setPhone(phone);
        insertUser.setPassword(MD5.encrypt(password));
        insertUser.setNickname(phone);
        int insert = baseMapper.insert(insertUser);
        if (insert == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    //手机验证更改密码
    @Override
    public boolean changePasswordForPhone(String phone, String code, String password) {

        String realCode = redisTemplate.opsForValue().get(phone);

        if (!code.equals(realCode)) return false;

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);

        User user = baseMapper.selectOne(queryWrapper);

        if (user == null) return false;

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("password", MD5.encrypt(password));

        int update = baseMapper.update(user, updateWrapper);

        return update == 1;
    }

    //新老密码更改密码
    @Override
    public boolean changePassword(String phone, String oldPassword, String newPassword) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.eq("password", MD5.encrypt(oldPassword));

        User user = baseMapper.selectOne(queryWrapper);
        if (user == null) return false;

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("password", oldPassword);

        int update = baseMapper.update(user, updateWrapper);

        return update == 1;
    }

    //找回密码
    @Override
    public R findPassword(String phone, String code) {

        String realCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(realCode)) return R.error();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);

        User user = baseMapper.selectOne(queryWrapper);
        if (user == null) return R.error();

        return R.ok().data("password", MD5.encrypt(user.getPassword()));
    }

    //修改个人信息
    @Override
    public boolean changeInfo(User user) {

        user.setPassword(MD5.encrypt(user.getPassword()));
        baseMapper.update(user, null);

        return true;
    }

    //手机号换绑
    @Override
    public boolean changePhone(String oldPhone, String newPhone, String password) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", oldPhone);
        queryWrapper.eq("password", MD5.encrypt(password));

        User user = baseMapper.selectOne(queryWrapper);
        if (user == null) return false;

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("phone", newPhone);

        int update = baseMapper.update(user, updateWrapper);
        return update == 1;
    }
}
